<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form
            size="small"
            ref="searchFormRef"
            :model="searchForm"
            layout="inline"
            label-align="right"
          >
            <a-form-item label="公司" field="firm">
              <a-cascader
                v-model="searchForm.firmId"
                :options="firmOptions"
                allow-clear
                class="bacClass"
                :style="{ width: '220px' }"
                popup-container="html"
              />
            </a-form-item>
            <a-form-item label="出库单号">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="searchForm.stockOutCode"
                @press-enter="doRefresh"
              />
            </a-form-item>
            <a-form-item label="日期">
              <a-date-picker
                popup-container="html"
                v-model="searchForm.beginDate"
                :style="{ width: '230px' }"
                class="bacClass"
              />
            </a-form-item>
            <a-form-item label="至">
              <a-date-picker
                popup-container="html"
                v-model="searchForm.endDate"
                :style="{ width: '240px' }"
                class="bacClass"
              />
            </a-form-item>
            <a-form-item label="审核状态">
              <a-select
                popup-container="html"
                allow-clear
                class="bacClass"
                v-model="searchForm.auditState"
                @press-enter="doRefresh"
              >
                <a-option :value="2">全部</a-option>
                <a-option :value="0">未审核</a-option>
                <a-option :value="1">已审核</a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <el-button type="primary" :icon="Search" @click="selectHandler" v-hasPermi="['cpcck.cx']">查询</el-button>
        <el-button type="success" :icon="CirclePlus" @click="addInstock" v-hasPermi="['cpcck.xzcx']">新增出库</el-button>
        <el-button :icon="Coordinate" @click="auditHandler" v-hasPermi="['cpcck.sh']">审核</el-button>
        <el-button :icon="EditPen" @click="disAduitHandler" v-hasPermi="['cpcck.fs']">反审</el-button>
        <el-button :icon="Delete" @click="deleteHandler" v-hasPermi="['cpcck.sc']">删除</el-button>
        <el-button :icon="Printer" @click="printHandler" v-hasPermi="['cpcck.dy']">打印</el-button>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="onLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid
            ref="table1Ref"
            :configaggrid="configaggrid"
            @change:rowSelected="handleRowSelected"
          ></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <AddOrEditDrawer
      :title="drawerTitle"
      v-model:visible="addOrEditDrawerVisible"
      position="bottom"
      :data="transferData"
      @update:visible="handleDrawerClose"
      @getList="doRefresh"
    />
    <!-- 弹窗提示 -->
    <a-modal
      v-model:visible="tipModalConfig.visible"
      width="350px"
      @ok="tipModalOk"
      @cancel="tipModalConfig.visible = false"
    >
      <template #title>
        <span style="font-size: 16px; font-weight: 600; color: #000000">提示</span>
      </template>
      <div>确认要{{ tipModalConfig.contorlType }}当前数据吗?</div>
    </a-modal>
  </pageTabelLayout>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
  import { tableColumns } from './tableConfig/index.ts'
  import { post } from '@/api/http'
  import { Message } from '@arco-design/web-vue'
  import {
    Search,
    CirclePlus,
    Edit,
    Coordinate,
    EditPen,
    Delete,
    Printer,
  } from '@element-plus/icons-vue'
  import AddOrEditDrawer from './components/AddOrEditDrawer.vue'
  import emitter from '@/hooks/useEventBus.ts'
  import dayjs from 'dayjs'
  onMounted(() => {
    emitter.on('FinishedProductOutstock-edit', (data: any) => editHandler(data))
    getFirmOptions()
  })
  onBeforeUnmount(() => {
    emitter.off('FinishedProductOutstock-edit', (data: any) => editHandler(data))
  })
  const onLoading = ref<boolean>(false)
  const headerShow = ref<boolean>(true)
  const searchForm = reactive<any>({
    firmId: '',
    beginDate: '',
    endDate: '',
    auditState: 0,
    stockOutCode: '',
  })
  const searchFormRef = ref<any>(null)
  const firmOptions = ref<any>([])
  const drawerTitle = ref<string>('')
  //传递给抽屉的数据
  const transferData = reactive<any>({
    firmOptions: [],
    tableData: [],
    searchData: {},
    editAPIParams: {
      id: '',
    }, //修改接口参数
  })
  // 获取公司下拉框
  const getFirmOptions = () => {
    post({
      url: 'org/baCompany/getTreeCompanyByUser',
      data: {},
    }).then((result: any) => {
      if (result.code === 200) {
        firmOptions.value = result.data
        transferData.firmOptions = result.data
      } else {
        Message.error(result.message)
      }
    })
  }
  const table1Ref = ref<any>(null)
  let configaggrid = ref({
    url: 'wms/ProductStockOut/getPage', //接口路径
    queryData: {
      //接口参数
      companyId: searchForm.firmId,
      stockOutCode: searchForm.stockOutCode,
      beginDate: searchForm.beginDate,
      endDate: searchForm.endDate,
      auditState: searchForm.auditState == 2 ? null : searchForm.auditState,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns,
    fileName: 'finishedProductOutstock-1',
  })
  //勾选/取消勾选相同入库单号的行数据操作
  const handleRowSelected = (event: any) => {
    const { data, selected } = event.node
    table1Ref.value.forEachNode((node: any) => {
      const { stockOutCode } = node.data
      if (data.stockOutCode == stockOutCode) node.setSelected(selected)
    })
  }
  const doRefresh = async () => {
    try {
      if (onLoading.value) return
      onLoading.value = true
      await table1Ref.value.setQuery({
        companyId: searchForm.firmId,
        stockOutCode: searchForm.stockOutCode,
        beginDate: searchForm.beginDate,
        endDate: searchForm.endDate,
        auditState: searchForm.auditState == 2 ? null : searchForm.auditState,
      })
    } catch (e) {
      console.log(e)
    } finally {
      onLoading.value = false
    }
  }
  const selectHandler = () => {
    doRefresh()
  }
  const addOrEditDrawerVisible = ref<boolean>(false)
  //新增入库按钮
  const addInstock = () => {
    drawerTitle.value = '新增出库'
    addOrEditDrawerVisible.value = true
  }
  //修改按钮
  const editHandler = async (data: any) => {
    transferData.editAPIParams.id = data.id
    transferData.searchData = data
    drawerTitle.value = '修改'
    addOrEditDrawerVisible.value = true
  }
  const tipModalConfig = reactive({
    contorlType: '',
    visible: false,
  })
  //审核按钮
  const auditHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行审核')
      return
    }
    if (table1Ref.value.getSelectedRows().some((item: any) => item.auditState == 1)) {
      Message.error('已审核的数据不能进行审核')
      return
    }
    tipModalConfig.contorlType = '审核'
    tipModalConfig.visible = true
  }
  //反审按钮
  const disAduitHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行反审')
      return
    }
    if (table1Ref.value.getSelectedRows().some((item: any) => item.auditState == 0)) {
      Message.error('未审核的数据不能进行反审')
      return
    }
    tipModalConfig.contorlType = '反审'
    tipModalConfig.visible = true
  }
  const tipModalOk = async () => {
    try {
      if (tipModalConfig.contorlType == '审核') {
        const data = JSON.parse(JSON.stringify(table1Ref.value.getSelectedRows()))
        const uniqueObj = data.reduce((acc: any, cur: any) => {
          acc[cur.id] = {
            id: cur.id,
            auditState: 1,
          }
          return acc
        }, {})
        const uniqueArr = Object.values(uniqueObj)
        const res = await post({
          url: '/wms/ProductStockOut/setAudit',
          data: uniqueArr,
        })
        if (res.code == 200) {
          tipModalConfig.visible = false
          Message.success(res.message)
          doRefresh()
        } else {
          Message.error(res.message)
        }
      } else if (tipModalConfig.contorlType == '删除') {
        const res = await post({
          url: '/wms/ProductStockOut/delete',
          data: [...new Set(table1Ref.value.getSelectedRows().map((item: any) => item.id))],
        })
        if (res.code == 200) {
          tipModalConfig.visible = false
          Message.success(res.message)
          doRefresh()
        } else {
          Message.error(res.message)
        }
      } else if (tipModalConfig.contorlType == '反审') {
        const data = JSON.parse(JSON.stringify(table1Ref.value.getSelectedRows()))
        const uniqueObj = data.reduce((acc: any, cur: any) => {
          acc[cur.id] = {
            id: cur.id,
            auditState: 0,
          }
          return acc
        }, {})
        const uniqueArr = Object.values(uniqueObj)
        const res = await post({
          url: '/wms/ProductStockOut/setBackAudit',
          data: uniqueArr,
        })
        if (res.code == 200) {
          tipModalConfig.visible = false
          Message.success(res.message)
          doRefresh()
        } else {
          Message.error(res.message)
        }
      }
    } catch (e) {
      console.log(e)
    }
  }
  //删除按钮
  const deleteHandler = () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行删除')
      return
    }
    tipModalConfig.contorlType = '删除'
    tipModalConfig.visible = true
  }
  //打印按钮
  const printHandler = async () => {
    if (table1Ref.value.getSelectedRows().length == 0) {
      Message.error('请选择一条或多条数据进行打印')
      return
    }
    try {
      const idArr = table1Ref.value.getSelectedRows().map((item: any) => item.id)
      const res = await post({
        url: '/wms/ProductStockOut/getProductStockOutPrint',
        data: idArr,
      })
      if (res.code == 200) {
        const renderBody = (rowArr: any) => {
          const htmlStr = rowArr
            .map((item: any) => {
              return ` <tr>
                <td>${item.orderCode}</td>
                <td>${item.brandName}</td>
                <td>${item.clothCode}</td>
                <td>${item.colorCode}</td>
                <td>${item.colorName}</td>
                <td>${item.circulatCard}</td>
                <td>${item.weight}</td>
                <td>1</td>
            </tr>`
            })
            .join('')
          return htmlStr
        }
        const html = res.data.reduce((acc: any, cur: any) => {
          return (
            acc +
            `
    <!--startprint-->
    <div class="container" style="page-break-after:always">
    <div class="header">佛山市巨丰盛布业有限公司</div>
    <div class="sub-header">成品发货单</div>
    <div class="header-1">
        <div class="header-row-1">
            <div class="left-box">
                <span class="title">仓库:&nbsp;</span>
                <span>${cur.warehouseName}</span>
            </div>
            <div class="right-box">
                <span class="title">去向:&nbsp;</span>
                <span>${cur.customName}</span>
            </div>
        </div>
        <div class="header-row-2">
            <div class="left-box">
                <span class="title">发货单号:&nbsp;</span>
                <span>${cur.stockOutCode}</span>
            </div>
            <div class="mid-box">
                <span class="title">发货类型:&nbsp;</span>
                <span>${cur.stockOutTypeTypeName}</span>
            </div>
            <div class="right-box">
                <span class="title">开单日期:&nbsp;</span>
                <span>${dayjs(cur.createTime).format('YYYY-MM-DD')}</span>
            </div>
        </div>
    </div>
    <div class="content">
        <table>
            <thead>
            <tr>
                <th>订单号</th>
                <th>品名</th>
                <th>布号</th>
                <th>色号</th>
                <th>色称</th>
                <th>流转卡号</th>
                <th>重量（公斤）</th>
                <th>匹数</th>
            </tr>
            </thead>
            <tbody>
           ${renderBody(cur.ProductStockOutDetail)}
            <!-- 合计-->
            <tr style="background-color: #d9dee9;">
                <td colspan="6">合计：</td>
                <td>${cur.weight}</td>

                <td>${cur.horseNum}</td>
            </tr>
            <!-- 备注-->
            <tr id="left-tr">
                <td colspan="8">
                    备注：${cur.remark}
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <!-- 底部-->
    <div class="footer-box">
        <div class="footer-1">
            <div class="footer-item">
                制单人：${cur.createName}
            </div>
            <div class="footer-item">
                经办人：
            </div>
            <div class="footer-item">
                审核：
            </div>
            <div class="footer-item">
                检验：
            </div>
            <div class="footer-item">
                客户签收:
            </div>
        </div>
        <div class="footer-1">
            <div class="footer-item">
                白联财务：
            </div>
            <div class="footer-item">
                粉联仓库：
            </div>
            <div class="footer-item">
                绿联随货同行：
            </div>
            <div class="footer-item">
                蓝联统计：
            </div>
            <div class="footer-item">
                黄联出门：
            </div>
        </div>
    </div>
</div>
<!--endprint-->
    `
          )
        }, '')
        const style = `
    body, html {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            height: 100%;
        }

        .container {
            display: flex;
            flex-direction: column;
            width: 816.58px;
            height: 528.24px;
            margin: 0 auto;
            padding: 20px;
            box-sizing: border-box;
        }

        .header, .footer {
            text-align: center;
            padding: 10px 0;
        }

        .header {
            font-size: 24px;
            font-weight: bold;
        }

        .sub-header {
            text-align: center;
            font-size: 18px;
            margin-top: 10px;
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        th, td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: center;
        }

        th {
            background-color: #d9dee9;
        }

        .footer {
            padding-top: 20px;
            font-size: 14px;
        }

        .footer-buttons {
            text-align: center;
            margin-top: 20px;
        }

        .footer-buttons button {
            padding: 10px 20px;
            font-size: 16px;
            margin: 0 10px;
            cursor: pointer;
        }

        .header-1 {
            width: 100%;
            color: #555556;
        }

        .header-row-1 {
            width: 100%;
            display: flex;
        }

        .header-row-1 .left-box {
            width: 50%;
        }

        .header-row-1 .right-box {
            width: 50%;
        }

        .header-row-2 {
            width: 100%;
            display: flex;
        }

        .header-row-2 .left-box {
            width: 50%;
        }

        .header-row-2 .mid-box {
            width: 25%;
        }

        .header-row-2 .right-box {
            width: 25%;
            text-align: right;
        }

        .title {
            width: 80px;
            display: inline-block;
            text-align: right;
        }

        #left-tr td {
            text-align: left;
            padding-left: 30px;
        }

        .content {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .footer-box {
            margin-top: auto;
        }

        .footer-1 {
            width: 100%;
            display: flex;
            font-size: 12px;
        }

        .footer-item {
            width: 20%;
            text-align: left;
            color: #555556;
        }
    `
        localStorage.setItem('currentPrintHtml', html)
        localStorage.setItem('currentPrintStyle', style)
        var w = window.innerWidth * 0.7
        var h = window.innerHeight * 0.7
        window.open(
          'PrintWindow/index.html',
          '打印',
          'height=' +
            h +
            ', width=' +
            w +
            ', top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'
        )
      } else {
        Message.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const handleDrawerClose = (visible: boolean) => {
    addOrEditDrawerVisible.value = visible
    transferData.searchData = {} //清空表单数据
    transferData.tableData = []
  }
</script>
<style scoped>
  #Table td,
  #Table th {
    border: 1px solid #ccc;
    padding: 10px;
  }

  .tdStyle {
    min-width: 100px;
  }

  .notClick {
    background-color: gray;
    cursor: no-drop;
  }

  :deep(.SendCheck) {
    z-index: 100 !important;
  }

  :deep(.arco-table-th) {
    border-right: 1px solid var(--color-neutral-3);
  }

  :deep(.arco-table-td) {
    border-right: 1px solid var(--color-neutral-3);
  }
  .my-tool-bar {
    padding: 5px;
  }
</style>
